package com.qdairlines.controller.base;

import com.qdairlines.common.ADUtil;
import com.qdairlines.common.MD5Encoder;
import com.qdairlines.common.WxLinkUtil;
import com.qdairlines.constant.BaseConsts;
import com.qdairlines.entity.user.User;
import com.qdairlines.service.user.impl.UserServiceImpl;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("login")
public class LoginController {

	@Autowired
	private UserServiceImpl userServiceImpl;
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	//原来的登录地址
	@RequestMapping("withoutCas")
	public String login(HttpServletRequest request, Model model,
			HttpSession session) {
		//获取用户名和密码
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		//若用户名为空，则为通过这个请求进入登录页面，返回登录页面
		if(userName==null){
			return "/login";
		}
		if(password==null||password.trim().equals("")){
			return "/login";
		}
		if(ADUtil.checkUserPassword(userName, password)){
			CasToken token = new CasToken("");
			Subject currentUser = SecurityUtils.getSubject();
			token.setUserId(userName);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				e.printStackTrace();
				logger.error("用户名或者密码错误");
			}
			//登录成功后跳转到进入首页的方法
			return "redirect:toMainPage.do";
		}
		//不为空时，通过输入的用户名获取该用户
		User user = userServiceImpl.getUserByUserName(userName);
		if(BaseConsts.POJO_STATUS_DISABLE.equals(user.getStatus())){
			return "/login";
		}
		//if（用户名和密码匹配，则认定为登录成功）
		if (user != null
				&& user.getPassword().equals(
						MD5Encoder.encode(password))) {
			//模拟从cas跳转过来登录的过程，手动创建CasToken CasToken中有3个属性，userId，ticket和remeberMe
			//正常cas跳转过来是有ticket属性 无userId属性，我们模拟过程时，set进入userId
			//登录时通过判断userId是不是为空来判断是正常cas登录还是手动登录，详见MyCasRealm
			CasToken token = new CasToken("");
			Subject currentUser = SecurityUtils.getSubject();
			token.setUserId(userName);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				e.printStackTrace();
				logger.error("用户名或者密码错误");
			}
			//登录成功后跳转到进入首页的方法
			return "redirect:toMainPage.do";
		} else {
			//如果用户名密码不正确则返回登录页面
			return "/login";
		}
	}

	@RequestMapping("toMainPage")
	public String index(HttpServletRequest request, Model model,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		
		String language = request.getLocale().getLanguage(); //浏览器默认语言;
		System.out.print("language>>>>>>>>>>>>>"+language);
		User user = (User) session.getAttribute("currentUser");
		if(user == null){
			return "/login";
		}
		if(BaseConsts.POJO_STATUS_DISABLE.equals(user.getStatus())){
			return "/login";
		}
		return "/test";
	}

	@RequestMapping("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		}
		return "redirect:http://platform.qdairlines.com/logout?service=http://platform.qdairlines.com";
	}

	@ResponseBody
	@RequestMapping("getUserUrls")
	public String getUserUrls(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("currentUser");
		return JSONObject.fromObject(user).toString();
	}

	
/**
 * 微信登录入口
 * @param request
 * @param model
 * @return
 */
    @RequestMapping(value="loginByWx", produces = "text/html;charset=UTF-8")
    public String loginByWx(HttpServletRequest request,Model model){
    	//接收加密参数
    	String key = request.getParameter("key");	
    	
    	//根据加密参数key请求返回workcode
    	//key值有效生命周期为30秒，超过30秒即销毁。
    	//key值有效次数为1次，请求wxlink一次后，无论是否返回成功，wxlink立刻销毁该key
    	String workcode  = WxLinkUtil.getWorkcode(key);
    

    	String redirectUrl = request.getParameter("redirectUrl");
    	//WxLinkUtil.validateWorkcode是用来验证转发消息是否是本人打开的
		if(!StringUtils.isEmpty(workcode)&&!StringUtils.isEmpty(redirectUrl) && WxLinkUtil.validateWorkcode(redirectUrl, workcode)){
				//如果有转发请求的话，在MQ消息中封装的重定向地址中，应当包含此参数，也建议就使用该参数名称
				return "redirect:"+WxLinkUtil.redirectUrlDecode(redirectUrl);
		
		}else if(!StringUtils.isEmpty(workcode)){
			//只是集成登录，并没有转发请求，则进入登录后首页
			return "/index";
			
		}else{
			return "/login";
		}
    }
}
